//
//  MainViewController.m
//  YaDiuDiu
//
//  Created by 欧洪飞 on 2017/8/23.
//  Copyright © 2017年 jy. All rights reserved.
//

#import "MainViewController.h"

#import "MainCell.h"
#import "QDViewController.h"
#import "TimeView.h"
#import "CheXianViewController.h"
#import "HBView.h"

#import "MainDetViewController.h"
#import "NearplaceViewController.h"

#import "NavViewController.h"
#import "LoginViewController.h"
#import "HomeCollectionViewCell.h"
#import "SeckillModel.h"
#import "GoodsModel.h"
#import "MJExtension.h"
#import "iflyMSC/IFlyMSC.h"
#import "SDCycleScrollView.h"
@interface MainViewController ()<UITableViewDelegate,UITableViewDataSource,BMKMapViewDelegate,BMKLocationServiceDelegate,BMKGeoCodeSearchDelegate,NearplaceViewControllerDelegate,UICollectionViewDelegate,UICollectionViewDataSource,IFlySpeechSynthesizerDelegate,SDCycleScrollViewDelegate,HBViewDelegate>{
    HBView *hbview;
    UIView *view;//
    NSTimer *time;
    BMKMapView *mapView;
    BMKLocationService *location;
    BMKGeoCodeSearch *geocodeSearch;
    UIButton *btn;
    UILabel *labPeople;//消费人数
    UILabel *labMoney;//消费金额
    CGFloat lat;
    CGFloat lng;
    NSUInteger _timeCount;
    BOOL _isAll;//标记colectioviewcell是不是都没选中
    NSInteger _lastCell;//记录上个cell
    NSInteger _currentCell;//记录当前的cell
    NSUInteger _time;
}

@property (nonatomic,strong)UITableView *tableView;
@property (nonatomic,strong)NSMutableArray *array;//秒杀产品
@property (nonatomic,strong)NSMutableArray *dataBanaer;//
@property (nonatomic,strong)NSMutableDictionary *dic;
@property (nonatomic,strong)UILabel *labText;

@property (nonatomic, strong)  NSTimer *labelTimer;

@property (nonatomic, strong) UICollectionView *seckillCollection;

@property (nonatomic, strong) NSMutableArray *seckillArray;

//@property (nonatomic, strong) NSMutableArray *seckillProductArray;

@property (nonatomic, strong) NSString *selIndeString;

@property (nonatomic, assign) long dajiTime;

@property (nonatomic, assign) BOOL isMiaosha;

@property (nonatomic, strong) NSString *iFlySpeechVoice;

@property (nonatomic, assign) NSInteger selcollindex;

@property (nonatomic, strong) TimeView *tableHeardTimeView;

@property (nonatomic, assign) NSInteger animationIndex;

@property (nonatomic, strong) IFlySpeechSynthesizer *iFlySpeechSynthesizer;

@property (nonatomic, strong) NSMutableDictionary *voiceDic;
@property(nonatomic,strong)SDCycleScrollView *cycleView;
@property (nonatomic, assign) NSInteger miaos;

@property (nonatomic, assign) NSInteger miaoh;

@property (nonatomic, assign) NSInteger miaom;
@property(nonatomic,strong)NSTimer *mainTimer;//计时器
/*秒杀模块的model*/
@property(nonatomic,strong)SeckillModel *seckilModel;
/*装秒杀相关的模型*/
@property(nonatomic,strong)NSArray *seckilModelArr;
/*商品相关model*/
@property(nonatomic,strong)NSArray *shopsModelArr;
@end

@implementation MainViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"hbVoice"] boolValue]== YES) {
        self.iFlySpeechVoice = @"0";
    }else{
        self.iFlySpeechVoice = @"50";
    }
    
    
    self.view.backgroundColor = COLOR_RGB(242, 242, 242, 1);
    _currentCell = 0;//秒杀默认选择
    [user setObject:@"http://diudiujituan.com" forKey:@"ImageUrl"];
    _dic = [NSMutableDictionary dictionary];
    _dataBanaer = [NSMutableArray array];
    [self loadVoiceData];
    [self loadHbData];
    [self loadData];
    [self loadMap];
    _isAll = NO;//默认都没选中
}
//百度地图定位
- (void)loadMap{
    location = [[BMKLocationService alloc] init];
    [location startUserLocationService];
    
    //显示定位图层
    mapView.showsUserLocation = YES;
    
    //反编码
    geocodeSearch = [[BMKGeoCodeSearch alloc] init];
    geocodeSearch.delegate = self;
}

- (void)loadVoiceData{
    NSString *url = [NSString stringWithFormat:@"%@/App/Norm/langechinse",urlHead];
    [[AFHTTPSessionManager manager] POST:url parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        NSInteger error = [[responseObject objectForKey:@"error"] integerValue];
        NSArray *dataArr = [responseObject objectForKey:@"result"];
        if (error == 200 && [dataArr isKindOfClass:[NSArray class]]) {
            self.voiceDic = [dataArr firstObject];
        }
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"error:%@",error);
    }];
}

-(void)viewWillAppear:(BOOL)animated{
    [mapView viewWillAppear];
    location.delegate = self;
}

-(void)viewWillDisappear:(BOOL)animated{
    [mapView viewWillDisappear];
    location.delegate = nil;
}

#pragma -mark BMKLocationServiceDelegate
-(void)didUpdateUserHeading:(BMKUserLocation *)userLocation{
    [mapView updateLocationData:userLocation];
    mapView.centerCoordinate = userLocation.location.coordinate;
    
}

-(void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation{
    NSLog(@"didUpdateUserLocation lat %f,long %f",userLocation.location.coordinate.latitude,userLocation.location.coordinate.longitude);
    lat = userLocation.location.coordinate.latitude;
    lng = userLocation.location.coordinate.longitude;
    [mapView updateLocationData:userLocation];
    mapView.centerCoordinate = userLocation.location.coordinate;
    
    //获取城市
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    [geocoder reverseGeocodeLocation:userLocation.location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        
        if (placemarks > 0) {
            CLPlacemark *mark = [placemarks objectAtIndex:0];
            if (mark) {
                
                NSLog(@"name:%@",mark.subLocality);
                NSLog(@"b%@",mark.locality);
                NSString *city = mark.locality;
                NSLog(@"c%@",mark.subLocality);
                if (!city) {
                    city = mark.administrativeArea;
                }
                
//                [btn setTitle:city forState:UIControlStateNormal];
            }
        }
    }];
    
    BMKReverseGeoCodeOption *reverseGeocodeSearchOption = [[BMKReverseGeoCodeOption alloc]init];
    
    reverseGeocodeSearchOption.reverseGeoPoint = userLocation.location.coordinate;
    
    BOOL flag = [geocodeSearch reverseGeoCode:reverseGeocodeSearchOption];
    if(flag){
        NSLog(@"反geo检索发送成功");
        //停止定位
        [location stopUserLocationService];
        
    }else{
        NSLog(@"反geo检索发送失败");
    }
    //停止定位
    [location stopUserLocationService];
}
//反检索
-(void)onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error{
    
    NSLog(@"%@---%@---%@--%@",result.addressDetail,result.address,result.businessCircle,result.addressDetail.district);
    NSLog(@"city:%@",result.cityCode);
    NSString *addressStr = [NSString stringWithFormat:@"%@",result.address];
    
    if (addressStr.length>9) {
        
        NSString *nAddress = [addressStr substringWithRange:NSMakeRange(0, 9)];
        [btn setTitle:[NSString stringWithFormat:@" %@...",nAddress] forState:UIControlStateNormal];

    }else
    {
        [btn setTitle:[NSString stringWithFormat:@" %@",addressStr] forState:UIControlStateNormal];
    }
}

-(void)didFailToLocateUserWithError:(NSError *)error{
    NSLog(@"定位失败：-------------error:%@",error);
}
#pragma -mark NearplaceViewControllerDelegate
-(void)sendPlace:(NSString *)text{
    [btn setTitle:text forState:UIControlStateNormal];
}
/*
  红包雨接口
 */
- (void)loadHbData{
    NSString *userid = [user objectForKey:@"userid"];
    if (userid.length > 0) {
        NSMutableDictionary *parmas = [NSMutableDictionary dictionary];
        [parmas setValue:userid forKey:@"id"];
        
        NSString *url = [NSString stringWithFormat:@"%@/App/Voucher/time",urlHead];
        [[AFHTTPSessionManager manager] POST:url parameters:parmas success:^(NSURLSessionDataTask *task, id responseObject) {
            NSInteger error = [[responseObject objectForKey:@"error"] integerValue];
            NSDictionary *dataDic = [responseObject objectForKey:@"result"];
            if (error == 200) {
                [self isShowHbView:dataDic];
            }
            
        } failure:^(NSURLSessionDataTask *task, NSError *error) {
            NSLog(@"error:%@",error);
        }];
    }
}

/*
 根据时间是不是显示红包雨
 */
- (void)isShowHbView:(NSDictionary *)dataDic{
    
    NSArray *timeArray = [dataDic objectForKey:@"time"];
    NSInteger diff = [[dataDic objectForKey:@"config"] integerValue];
    diff = diff / 60;
    NSString *nTime = [self getyNowTimeDayHour];
    nTime = [nTime substringToIndex:[nTime length] - 1];
    for (int i = 0; i < timeArray.count; i ++) {
        NSDictionary *tdic = [timeArray objectAtIndex:i];
        NSString *t = [tdic objectForKey:@"time"];
        NSArray *tt = [t componentsSeparatedByString:@":"];
        NSInteger ntimeInt = [nTime integerValue];
        NSInteger btt = [[tt firstObject] integerValue];
        if (ntimeInt == btt) {
            NSString *nmin = [self getyNowTimeDayMinute];
            NSInteger nminInt = [nmin integerValue];  //现在时间
            NSInteger bmm = [[tt objectAtIndex:1] integerValue]; //红包开始时间
            // 红包正在抢的
            if (nminInt >= bmm && nminInt <= (bmm + diff)) {
                [self loadHBView:(bmm + diff) - nminInt];
                [hbview loadHongBaoUserData:dataDic selindex:i];
                [self playHongBaoyuyin:@"red"];
            }
            // 时间还没到 提前5分钟进入
            if (nminInt < bmm && nminInt > bmm - 5) {
                [self loadHBView:bmm + diff + (bmm - nminInt)];
                [hbview loadHongBaoUserTiQianData:dataDic Tiqian:bmm - nminInt];
                [self playHongBaoyuyin:@"red"];
            }
        }
        
    }
    
}

- (void)playHongBaoyuyin:(NSString *)string{
    
    NSString *voiceSting = @"";
    if (self.voiceDic) {
        voiceSting = [self.voiceDic objectForKey:string];
    }
    self.iFlySpeechSynthesizer = [IFlySpeechSynthesizer sharedInstance];
    //设置协议委托对象
    self.iFlySpeechSynthesizer.delegate = self;
    //设置合成参数
    //设置在线工作方式
    [self.iFlySpeechSynthesizer setParameter:[IFlySpeechConstant TYPE_CLOUD] forKey:[IFlySpeechConstant ENGINE_TYPE]];
    //设置音量，取值范围 0~100
    [self.iFlySpeechSynthesizer setParameter:self.iFlySpeechVoice forKey: [IFlySpeechConstant VOLUME]];
    //发音人，默认为”xiaoyan”，可以设置的参数列表可参考“合成发音人列表”
    [self.iFlySpeechSynthesizer setParameter:@"xiaoyan" forKey: [IFlySpeechConstant VOICE_NAME]];
    //保存合成文件名，如不再需要，设置为nil或者为空表示取消，默认目录位于library/cache下
    [self.iFlySpeechSynthesizer setParameter:@"tts.pcm" forKey: [IFlySpeechConstant TTS_AUDIO_PATH]];
    //启动合成会话
    [self.iFlySpeechSynthesizer startSpeaking:voiceSting];
}

- (void) onCompleted:(IFlySpeechError *) error {
    
}
//合成开始
- (void) onSpeakBegin {
    
}
//合成缓冲进度
- (void) onBufferProgress:(int) progress message:(NSString *)msg {
    
}
//合成播放进度
- (void) onSpeakProgress:(int) progress beginPos:(int)beginPos endPos:(int)endPos {
    
}

- (NSString *)getyNowTimeDayHour{
    NSDate *date = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"hh"];
    NSString *DateTime = [formatter stringFromDate:date];
    return DateTime;
}

- (NSString *)getyNowTimeDayMinute{
    NSDate *date = [NSDate date];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"mm"];
    NSString *DateTime = [formatter stringFromDate:date];
    return DateTime;
}

//红包页面
- (void)loadHBView:(CGFloat)show{
    show = show * 60;
    if (show > 0) {
        show = show - 30;
    }
    [time invalidate];
    time = [NSTimer scheduledTimerWithTimeInterval:show target:self selector:@selector(sleep) userInfo:nil repeats:NO];
    hbview = [[[NSBundle mainBundle] loadNibNamed:@"HBView" owner:nil options:nil] lastObject];
    [hbview setDelegate:self];
    hbview.frame = CGRectMake(0, 0, ScreenWidth, ScreenHeight-49);
    [self.view addSubview:hbview];
    [self.view bringSubviewToFront:hbview];
  
    
}

#pragma mark ======HBViewDelegate
- (void)changeVoice:(BOOL)isb{
    if (isb == YES) {
        self.iFlySpeechVoice = @"0";
    }else{
        self.iFlySpeechVoice = @"50";
    }
}

//定时器
- (void)sleep{
    hbview.hidden = YES;
    [time invalidate];
    
}

//初始化轮播图
-(SDCycleScrollView *)cycleView
{
    if (!_cycleView) {
        
        _cycleView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(0, 0, ScreenWidth, 166) delegate:self placeholderImage:[UIImage imageNamed:@""]];
    }
    
    return _cycleView;
}
//导航栏相关
- (void)loadNav{
    view = [[UIView alloc] init];
    view.backgroundColor = [UIColor whiteColor];
    view.userInteractionEnabled = YES;
    [self.view addSubview:view];
    //自定义导航栏的约束
    [view mas_makeConstraints:^(MASConstraintMaker *make) {
    
        make.left.right.equalTo(self.view);
        make.height.mas_equalTo(64);
        make.top.equalTo(self.view.top);
        
    }];
    
    UILabel *line = [[UILabel alloc] init];
    line.backgroundColor = [UIColor lightGrayColor];
    [view addSubview:line];
    
    [line makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(0);
        make.right.equalTo(0);
        make.bottom.equalTo(view.bottom);
        make.height.equalTo(0.5);
    }];
    
    btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.titleEdgeInsets = UIEdgeInsetsMake(0, 0, 0, -10);
    [btn setImage:[UIImage imageNamed:@"-定位选择城市"] forState:UIControlStateNormal];
    [btn setImage:[UIImage imageNamed:@"-定位选择城市"] forState:UIControlStateSelected];
    [btn setTitle:@" 正在定位中..." forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
    btn.titleLabel.font = [UIFont systemFontOfSize:13.0];
    btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    btn.titleLabel.textAlignment = NSTextAlignmentLeft;
    [btn addTarget:self action:@selector(selectCity) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:btn];
    
    //btn的约束
    [btn mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.mas_equalTo(10);
        make.top.equalTo(view).offset(20);
        make.height.mas_offset(44);
    }];
    
    
    UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"箭头2"]];
    [view addSubview:imageView];
    //箭头imageview的约束
    [imageView makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(btn.right);
        make.centerY.equalTo(btn.centerY);
    }];
    
    
    UIButton *btn2 = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn2 setImage:[UIImage imageNamed:@"签到-(2)"] forState:UIControlStateNormal];
    [btn2 setImage:[UIImage imageNamed:@"签到-(2)"] forState:UIControlStateHighlighted];
    [btn2 setTitle:@" 签到" forState:UIControlStateNormal];
    [btn2 setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
    btn2.titleLabel.font = [UIFont systemFontOfSize:13.0];
    [btn2 addTarget:self action:@selector(clickQD) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:btn2];
    [btn2 makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(0);
        make.width.equalTo(60);
        make.height.equalTo(44);
        make.top.equalTo(btn);
    }];
    
}
//选择城市
- (void)selectCity{
    NearplaceViewController *place = [[NearplaceViewController alloc] init];
    place.lat = lat;
    place.lng = lng;
    place.delegate = self;
    [self.navigationController pushViewController:place animated:YES];
}
//签到
- (void)clickQD{
    if (![user objectForKey:@"userid"]) {
        LoginViewController *login = [[LoginViewController alloc] init];
        NavViewController *nav = [[NavViewController alloc] initWithRootViewController:login];
        nav.navigationBarHidden = YES;
        [self presentViewController:nav animated:YES completion:nil];
        return;
    }
    
    QDViewController *qd = [[QDViewController alloc] init];
    [self.navigationController pushViewController:qd animated:YES];
}
/*
 初始化tableview
 */
- (void)loadUI{
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, ScreenWidth, ScreenHeight-64-49) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableView];
    
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 380)];
    headView.backgroundColor = COLOR_RGB(242, 242, 242, 1);
    
    _tableView.tableHeaderView = headView;
    
    UILabel *lablines = [[UILabel alloc] initWithFrame:CGRectMake(0, 370, ScreenWidth, 10)];
    lablines.backgroundColor = COLOR_RGB(242, 242, 242, 1);
    [headView addSubview:lablines];
    
    //165+70+120+15
    NSMutableArray *arr = [NSMutableArray array];
    for (NSDictionary *op in _dataBanaer) {
        NSString *imgUrl = [NSString stringWithFormat:@"%@%@",[user objectForKey:@"ImageUrl"],[op objectForKey:@"banner"]];
        [arr addObject:imgUrl];
    }
    
    self.cycleView.imageURLStringsGroup = arr;
    
    //添加轮播图
    [headView addSubview:self.cycleView];
    
    UIView *view1 = [[UIView alloc] initWithFrame:CGRectMake(0, self.cycleView.frame.origin.y+self.cycleView.frame.size.height+5, ScreenWidth, 70)];
    view1.backgroundColor = [UIColor whiteColor];
    [headView addSubview:view1];
    
    //昨日消费人数
    labPeople = [[UILabel alloc] init];
    labPeople.text = @"0";
    labPeople.textColor = [UIColor redColor];
    labPeople.font = [UIFont systemFontOfSize:20.0];
    labPeople.textAlignment = NSTextAlignmentCenter;
    [view1 addSubview:labPeople];
    [labPeople makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(view1.top).offset(8);
        make.left.equalTo(view1.left);
        make.width.mas_equalTo(view1.width).multipliedBy(0.5);
    
    }];
    
    UILabel *labPSum = [[UILabel alloc] init];
    labPSum.text = @"昨日消费人数";
    labPSum.textColor = [UIColor blackColor];
    labPSum.font = [UIFont boldSystemFontOfSize:15.0];
    labPSum.textAlignment = NSTextAlignmentCenter;
    [view1 addSubview:labPSum];
    [labPSum makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(labPeople.centerX);
        make.top.equalTo(labPeople.bottom).offset(8);
        make.width.equalTo(view1.width).multipliedBy(0.5);
    }];
    
    //中间的红线
    UILabel *line = [[UILabel alloc] init];
    line.backgroundColor = [UIColor redColor];
    [view1 addSubview:line];
    [line makeConstraints:^(MASConstraintMaker *make) {
        make.width.equalTo(1);
        make.height.equalTo(30);
        make.top.equalTo(view1.top).offset(20);
        make.left.equalTo(labPSum.right);
    }];
    
    //成交金额
    labMoney = [[UILabel alloc] init];
    labMoney.text = @"0";
    labMoney.textColor = [UIColor redColor];
    labMoney.textAlignment = NSTextAlignmentCenter;
    labMoney.font = [UIFont systemFontOfSize:20.0];
    [view1 addSubview:labMoney];
    [labMoney makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(line.right).offset(0);
        make.top.equalTo(view1.top).offset(8);
        make.width.equalTo(labPSum.width);
    }];
    
    UILabel *labPJinE = [[UILabel alloc] init];
    labPJinE.text = @"昨日成交金额";
    labPJinE.textColor = [UIColor blackColor];
    labPJinE.font = [UIFont boldSystemFontOfSize:15.0];
    labPJinE.textAlignment = NSTextAlignmentCenter;
    [view1 addSubview:labPJinE];
    [labPJinE makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(labMoney.centerX);
        make.top.equalTo(labMoney.bottom).offset(8);
        make.width.equalTo(labPSum.width);

    }];
    
    UIView *view2 = [[UIView alloc] initWithFrame:CGRectMake(0, view1.frame.origin.y+view1.frame.size.height+5, ScreenWidth, 30)];
    view2.backgroundColor = [UIColor whiteColor];
    [headView addSubview:view2];
    
    UIImageView *image = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"公告-(2)"]];
    [view2 addSubview:image];
    [image makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(view2.left).offset(16);
        make.centerY.equalTo(view2.centerY);
        make.width.height.equalTo(14);
    }];
    
    UILabel *labGG = [[UILabel alloc] init];
    labGG.text = @"用户昵称";
    labGG.textColor = [UIColor redColor];
    labGG.font = [UIFont systemFontOfSize:13.0];
    [view2 addSubview:labGG];
//    [labGG makeConstraints:^(MASConstraintMaker *make) {
//        make.centerY.equalTo(image.centerY);
//        make.left.equalTo(image.right).offset(8);
//        make.width.equalTo(60);
//    }];
    
    //轮播广告
    
    SDCycleScrollView *titleScrollView = [SDCycleScrollView cycleScrollViewWithFrame:CGRectMake(30, 0, ScreenWidth - 40, 30) delegate:self placeholderImage:nil];;
    titleScrollView.scrollDirection = UICollectionViewScrollDirectionVertical;
    titleScrollView.onlyDisplayText = YES;
    titleScrollView.titleLabelBackgroundColor = [UIColor whiteColor];
    titleScrollView.titleLabelTextColor = [UIColor blackColor];
    titleScrollView.titleLabelTextFont = [UIFont systemFontOfSize:12];
    
    NSMutableArray *titlesArray = [NSMutableArray new];
    
    [view2 addSubview:titleScrollView];

    
    if ([_dic[@"OrderNotice"] isKindOfClass:[NSNull class]]) {
        
        [titlesArray addObjectsFromArray:@[]];
        titleScrollView.titlesGroup = [titlesArray copy];
        
    }else{
        
        NSArray *res = _dic[@"OrderNotice"];
        [titlesArray addObjectsFromArray:res];
        
        NSMutableArray *arr = [NSMutableArray array];
        for (int i = 0; i < res.count; i++) {
            NSDictionary *dic = res[i];
            [arr addObject:dic[@"ordername"]];
        }
        
        titleScrollView.titlesGroup = arr;
    }
    [view2 addSubview:_labText];
    
    
    UIView *view3 = [[UIView alloc] initWithFrame:CGRectMake(0, view2.frame.origin.y+view2.frame.size.height+5, ScreenWidth, 90)];
    view3.backgroundColor = [UIColor whiteColor];
    [headView addSubview:view3];
    
    UIImageView *image2 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"mszc"]];
    [view3 addSubview:image2];
    [image2 makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(view3.top).offset(8);
        make.left.equalTo(view3.left).offset(16);
    }];
    
    UILabel *labMS = [[UILabel alloc] init];
    labMS.text = @"限时秒杀，先到先得";
    labMS.textColor = [UIColor darkGrayColor];
    labMS.textAlignment = NSTextAlignmentRight;
    labMS.font = [UIFont systemFontOfSize:13.0];
    [view3 addSubview:labMS];
    [labMS makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(image2.centerY);
        make.right.equalTo(view3.right).offset(-16);
    }];
    
    UILabel *lab3L = [[UILabel alloc] init];
    lab3L.backgroundColor = COLOR_RGB(242, 242, 242, 1);
    [view3 addSubview:lab3L];
    [lab3L makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(image2.bottom).offset(8);
        make.right.equalTo(view3.right);
        make.left.equalTo(view3.left);
        make.height.equalTo(1);
    }];
    
    //初始化colletionview
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    layout.minimumLineSpacing = 0;
    layout.minimumInteritemSpacing = 0;
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    self.seckillCollection = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, 0, 0) collectionViewLayout:layout];
    [self.seckillCollection setDataSource:self];
    [self.seckillCollection setDelegate:self];
    [self.seckillCollection setShowsVerticalScrollIndicator:NO];
    [self.seckillCollection setShowsHorizontalScrollIndicator:NO];
    [self.seckillCollection setBackgroundColor:[UIColor whiteColor]];
    [self.seckillCollection registerClass:[HomeCollectionViewCell class] forCellWithReuseIdentifier:@"homeCell"];
    [view3 addSubview:self.seckillCollection];
    [self.seckillCollection mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(16);
        make.right.equalTo(-16);
        make.top.equalTo(lab3L.bottom);
        make.bottom.equalTo(0);
    }];
    
    
    [self.view bringSubviewToFront:hbview];
    NSString *people = [NSString stringWithFormat:@"%@",[self.dic objectForKey:@"ConsumerPopulation"]];
    NSString *money = [NSString stringWithFormat:@"%@",[self.dic objectForKey:@"TransactionAmount"]];
    labPeople.text = people;
    labMoney.text = money;
    NSArray *noticeArr = [self.dic objectForKey:@"OrderNotice"];
    if ([noticeArr isKindOfClass:[NSArray class]]) {
        [self.labelTimer invalidate];
        self.animationIndex = 0;
//        [self labelAnimation];
//        self.labelTimer = [NSTimer scheduledTimerWithTimeInterval:30.0 target:self selector:@selector(labelAnimation) userInfo:nil repeats:YES];
    }
    
}

#pragma  mark -- sycleDelegate
-(void)cycleScrollView:(SDCycleScrollView *)cycleScrollView didSelectItemAtIndex:(NSInteger)index
{
}

#pragma -mark UITableViewDataSource

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    SeckillModel *model = self.seckilModelArr[_currentCell];
    return model.good.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellId = @"Cell";
    MainCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (!cell) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"MainCell" owner:nil options:nil] lastObject];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    //拿到每个模块的数据
    SeckillModel *model = self.seckilModelArr[_currentCell];
    //商品模型
     self.shopsModelArr  = [GoodsModel mj_objectArrayWithKeyValuesArray:model.good];
    
    //商品模型
    GoodsModel *goodsModel = self.shopsModelArr[indexPath.row];
    //图片
    NSString *imgUrl = [NSString stringWithFormat:@"%@%@",[user objectForKey:@"ImageUrl"],goodsModel.img];
    [cell.images sd_setImageWithURL:[NSURL URLWithString:imgUrl] placeholderImage:[UIImage imageNamed:@""]];
    //商品描述
    cell.labTit.text = goodsModel.subject;
    //现在价格
    cell.labPrice1.text = [NSString stringWithFormat:@"￥%@",goodsModel.pprice];
    //以前的价格
    cell.labPrice2.text = [NSString stringWithFormat:@"￥%@",goodsModel.oprice];
    //进度
    NSInteger Proportion = [goodsModel.Proportion integerValue];
    [cell.num setText:[NSString stringWithFormat:@"已抢%zd%@",Proportion,@"%"]];
    
    float jj = cell.totalWith.constant / 100.0;
    cell.jinduWith.constant = jj * Proportion;
    
    //2: 开始抢购 3:暂无开始
    if ([model.isstart isEqualToString:@"2"]) {
        
        [cell.btn setBackgroundColor:HexColorInt32_t(FD1142)];
        cell.btn.enabled = YES;

    }else{
        
        [cell.btn setBackgroundColor:HexColorInt32_t(555555)];
        [cell.btn setTitle:@"立即抢购" forState:UIControlStateNormal];
        cell.btn.enabled = NO;
    }
   
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 130.0;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    self.tableHeardTimeView = [[[NSBundle mainBundle] loadNibNamed:@"TimeView" owner:nil options:nil] lastObject];
    self.tableHeardTimeView.frame = CGRectMake(0, 0, ScreenWidth, 55);
    
      SeckillModel *model = self.seckilModelArr[_currentCell];
    //状态
    if ([[self dateTimeBiJiao:model]isEqualToString:@"秒杀中"]) {
        
        //直接用后台的字段
        self.tableHeardTimeView.statusLabel.text = @"结束";
        
    }else
    {
        //自己计算时间
        self.tableHeardTimeView.statusLabel.text = @"开始";
    }
    
    return self.tableHeardTimeView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 55.0;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    MainDetViewController *det = [[MainDetViewController alloc] init];
    SeckillModel *model = self.seckilModelArr[_currentCell];
 
    //商品model
    GoodsModel *goodsModel = self.shopsModelArr[indexPath.row];
    //传值到下一个界面
    det.model = goodsModel;
    det.statue = model.isstart;
    NSLog(@"goodid---%@",goodsModel.id);
    
    [self.navigationController pushViewController:det animated:YES];
}
//秒杀页面数据
- (void)loadData{
    NSString *url = [NSString stringWithFormat:@"%@/App/Seckill/index",urlHead];
    [[AFHTTPSessionManager manager] POST:url parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        NSLog(@"res:%@",responseObject);
        NSString *status = [NSString stringWithFormat:@"%li",[[responseObject objectForKey:@"status"] integerValue]];
        if ([status integerValue] == 200) {
            
           
            _dic = responseObject;
            _dataBanaer = [responseObject objectForKey:@"banner"];
           
            //字典转模型
            NSArray *arr = [responseObject objectForKey:@"SeckillTime"];
            NSArray *secklModelArray  = [SeckillModel mj_objectArrayWithKeyValuesArray:arr];
            self.seckilModelArr = secklModelArray;
            
            // 防止刷新UI的时候创建多个定时器，导致多个定时器一起倒计时。
            if (!self.mainTimer) {
                [self startTimer];
            }
            
            [self.tableView reloadData];
            [self.seckillCollection reloadData];
        }
       
        [self loadNav];
        [self loadUI];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"error:%@",error);
    }];
    
}
/*
 倒计时相关 : 即将开始 秒杀中
 
    当前时间-time >= 0 已经开始 倒计时显示还有多长时间开始
    当前时间-time < 0 即将开始 倒计时显示还有多长时间结束
 
 */
- (NSString *)dateTimeBiJiao:(SeckillModel *)model{
    
    /*把当前时间和该时间戳进行对比*/
    NSString *startTimeString = model.time;
    //开始时间
   long long onetime = [startTimeString longLongValue];
    //获取当前时间
   long long nowtime = [[NSDate date] timeIntervalSince1970];

    //对比的时间 单位：秒
    long long compareTime = nowtime - onetime;
    if ( compareTime >= 0) {
        
        NSLog(@"对比的结果-已经开始--%lld-",compareTime);
        
        return @"秒杀中";
    }else{
        
        NSLog(@"一即将开始--%lld-",compareTime);
        return @"即将开始";
    }

    
}


/*
 计算倒计时间
 */
- (long long)dateTimeCompare:(SeckillModel *)model{
    
    /*把当前时间和该时间戳进行对比*/
    NSString *startTimeString = model.time;
    //开始时间
    long long onetime = [startTimeString longLongValue];
    //获取当前时间
    long long nowtime = [[NSDate date] timeIntervalSince1970];
    //对比的时间 单位：秒
    long long compareTime = nowtime - onetime;
    
    return compareTime;
    
}

//bug
- (void)labelAnimation{
<<<<<<< .mine
    NSArray *noticeArr = [self.dic objectForKey:@"OrderNotice"];
    if (self.animationIndex == noticeArr.count-1) {
        self.animationIndex = 0;
    }
    if (!noticeArr) {
        return;
    }
//    NSDictionary *labeDic = [noticeArr objectAtIndex:self.animationIndex];
//    NSString *nickname = [labeDic objectForKey:@"nickname"];
//    NSString *ordername = [labeDic objectForKey:@"ordername"];
//    [self.labText setText:[NSString stringWithFormat:@"%@ %@",nickname,ordername]];
    self.animationIndex ++;
||||||| .r207
    NSArray *noticeArr = [self.dic objectForKey:@"OrderNotice"];
    if (self.animationIndex == noticeArr.count-1) {
        self.animationIndex = 0;
    }
    NSDictionary *labeDic = [noticeArr objectAtIndex:self.animationIndex];
    NSString *nickname = [labeDic objectForKey:@"nickname"];
    NSString *ordername = [labeDic objectForKey:@"ordername"];
    [self.labText setText:[NSString stringWithFormat:@"%@ %@",nickname,ordername]];
    self.animationIndex ++;
=======
//    NSArray *noticeArr = [self.dic objectForKey:@"OrderNotice"];
//    if (self.animationIndex == noticeArr.count-1) {
//        self.animationIndex = 0;
//    }
//    NSDictionary *labeDic = [noticeArr objectAtIndex:self.animationIndex];
//    NSString *nickname = [labeDic objectForKey:@"nickname"];
//    NSString *ordername = [labeDic objectForKey:@"ordername"];
//    [self.labText setText:[NSString stringWithFormat:@"%@ %@",nickname,ordername]];
//    self.animationIndex ++;
>>>>>>> .r244
    
}

#pragma mark === UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.self.seckilModelArr.count;
}

- (__kindof UICollectionViewCell *)collectionView:(UICollectionView *)collectionView    cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    HomeCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"homeCell" forIndexPath:indexPath];
    if (cell == nil) {
        cell = [[HomeCollectionViewCell alloc]init];
    }
    
    SeckillModel *model = self.seckilModelArr[indexPath.row];
    //开始时间
    cell.timeLabel.text = [self dateChangeString:[self stingChangeToTime:model.starttime]];
 
    // 抢购状态
    cell.statusLabel.text = [self dateTimeBiJiao:model];

    if (_isAll == NO) {
        
        if (indexPath.row == 0) {
            
            model.select = YES;
          
        }
    }
    
    //判断颜色
    if (model.select == YES) {
        [cell.statusLabel setTextColor:HexColorInt32_t(FD1142)];
         [cell.timeLabel setTextColor:HexColorInt32_t(FD1142)];
    }else
    {
        [cell.statusLabel setTextColor:HexColorInt32_t(555555)];
        [cell.timeLabel setTextColor:HexColorInt32_t(555555)];
    }

    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{

    _currentCell = indexPath.row;

    // 防止刷新UI的时候创建多个定时器，导致多个定时器一起倒计时。
    if (self.mainTimer) {
        //释放
        [self.mainTimer invalidate];
        self.mainTimer = nil;
        //重新加载
        [self startTimer];
    }
    
    SeckillModel *model = self.seckilModelArr[indexPath.row];
    [self dateTimeBiJiao:model];

    _isAll = YES;//已经不需用了
    
    //点击cell，便利数组，让当前点击的模型选中，其他的不选中
   
    for (int i = 0; i < self.seckilModelArr.count; i++) {
        
        SeckillModel *model = self.seckilModelArr[i];
        
        if (i == indexPath.row) {
            
            model.select = YES;

        }else{
            
            model.select = NO;
        }
        
    }
    
    [self.seckillCollection reloadData];
    [self.tableView reloadData];
    
}



#pragma mark ---- UICollectionViewDelegateFlowLayout

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake((ScreenWidth-32)/5, 57) ;
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(0, 0, 0, 0);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 0;
}

/*
  字符串转nsdate
 */
-(NSDate *)stingChangeToTime:(NSString *)str
{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"HH-mm-sss"];
    NSDate *resDate = [formatter dateFromString:str];
    return resDate;
}

/*NSDate转字符串*/
-(NSString *)dateChangeString:(NSDate *)date
{
    NSDateFormatter *forrmater = [[NSDateFormatter alloc]init];
    forrmater.dateFormat = @"HH:mm";
    return [forrmater stringFromDate:date];
    
}


- (NSMutableArray *)seckillArray{
    if (!_seckillArray) {
        _seckillArray = [[NSMutableArray alloc]init];
    }
    return _seckillArray;
}

/*倒计时*/
-(void)startTimer{
    
    self.mainTimer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(refreshLessTime) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop]addTimer:self.mainTimer forMode:UITrackingRunLoopMode];
    
    SeckillModel *model = self.seckilModelArr[_currentCell];
    
    long long endTimes = [model.endtimes longLongValue];
    long long times = [model.time longLongValue];
    long long currentsTimes =   [[NSDate date] timeIntervalSince1970];
    //开始中 endtimes - nowTime  还有多久结束
    if ([model.isstart isEqualToString:@"2"]||[model.isstart isEqual:@2]) {
        
        long long compare =  endTimes - currentsTimes;
        _time = compare;
        [self lessSecondToDay:compare];
        
    }else if([model.isstart isEqualToString:@"3"])//即将开始
    {
        // time - nowTIme 还有多久开始
        long long compare =  times - currentsTimes;
        _time = compare;
        [self lessSecondToDay:compare];
        
    }
    
   
}
/*
 开始倒计时
 */
-(void)refreshLessTime
{
    NSInteger oldTime;
    if (_time == 0) {
        oldTime = 0;
    }else
    {
        oldTime = --_time;
    }
    
//    NSLog(@"---开始倒计时-%@--",[self lessSecondToDay:oldTime]);
    
    if (oldTime == 0) {
          
        //结束了在刷新哈数据
        [self loadData];
        [self countDownFinished];
    }else
    {
        self.miaos = oldTime % 60;
        self.miaom = (oldTime / 60) % 60;
        self.miaoh = oldTime/60/60 % 24;
        NSUInteger day  = (NSUInteger)oldTime/(24*3600);
        if (day > 0) {
            
            [self.tableHeardTimeView.dayLabel setText:[NSString stringWithFormat:@"还有 %lu天",(unsigned long)day]];

        }
        [self.tableHeardTimeView.shiLabel setText:[NSString stringWithFormat:@"%.2zd",self.miaoh]];
        [self.tableHeardTimeView.fenLabel setText:[NSString stringWithFormat:@"%.2zd",self.miaom]];
        [self.tableHeardTimeView.miaoLabel setText:[NSString stringWithFormat:@"%.2zd",self.miaos]];
        
    }
    
}
//根据秒数计算剩余时间：天，小时，分钟，秒
- (NSString *)lessSecondToDay:(NSUInteger)seconds
{
    NSUInteger day  = (NSUInteger)seconds/(24*3600);
    NSUInteger hour = (NSUInteger)(seconds%(24*3600))/3600;
    NSUInteger min  = (NSUInteger)(seconds%(3600))/60;
    NSUInteger second = (NSUInteger)(seconds%60);
    NSString *timeStr;
    if (seconds == 0) {
        timeStr = @"已结束";
        [self countDownFinished];
    }else {
        timeStr = [NSString stringWithFormat:@"%02zd天 %02zd:%02zd:%02zd",(unsigned long)day,(unsigned long)hour,(unsigned long)min,(unsigned long)second];
    }
    return timeStr;
}
- (void)countDownFinished
{
    [self.mainTimer invalidate];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
